<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-05-18 15:39:38
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-26 18:56:12
 * @FilePath: \ken147258.topayClient\src\views\payee\another-pay-management\components\UploadImage.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-upload
    flex
    flex-justify-between
    ref="upload"
    class="upload"
    v-model:file-list="fileList"
    :limit="1"
    :before-upload="handleBeforeUpload"
    :http-request="handleUpload"
    :on-exceed="handleExceed"
    :on-preview="previewImg"
  >
    <!-- <template #trigger> -->
    <el-button type="primary">请选择图片</el-button>
    <!-- </template> -->
  </el-upload>

  <el-dialog v-model="dialogVisible" width="360">
    <img w-full :src="previewImgUrl" />
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  UploadRequestOptions,
  UploadUserFile,
  UploadFile,
  genFileId,
} from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { uploadImage } from "@/api/payer/common";

const emit = defineEmits(["update:modelValue"]);

const props = defineProps({
  /**
   * 文件路径集合
   */
  modelValue: {
    type: Array<string>,
    default: () => [],
  },
  /**
   * 文件上传数量限制
   */
  // limit: {
  //   type: Number,
  //   default: 10,
  // },
});
const previewImgUrl = ref("");
const dialogVisible = ref(false);
const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()

  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file)
  upload.value!.submit();
}

const fileList = ref([] as UploadUserFile[]);
watch(
  () => props.modelValue,
  (newVal) => {
    const filePaths = fileList.value.map((file) => file.url);
    // 监听modelValue文件集合值未变化时，跳过赋值
    if (
      filePaths.length > 0 &&
      filePaths.length === newVal.length &&
      filePaths.every((x) => newVal.some((y) => y === x)) &&
      newVal.every((y) => filePaths.some((x) => x === y))
    ) {
      return;
    }

    if (newVal && newVal.length > 0) {
      fileList.value = newVal.toString().split().map((filePath) => {
        return { url: import.meta.env.VITE_APP_BASE_API + filePath,
          name: '图片', } as UploadUserFile;
      });
    } else {
      fileList.value.splice(0);
    }
  },
  { immediate: true }
);

/**
 * 自定义图片上传
 *
 * @param params
 */
async function handleUpload(options: UploadRequestOptions): Promise<any> {
  console.log(options.file)
  // 上传API调用
  const { path } = await uploadImage(options.file);

  const name = options.file.name;

  // 上传成功需手动替换文件路径为远程URL，否则图片地址为预览地址 blob:http://
  const fileIndex = fileList.value.findIndex(
    (file) => file.uid == (options.file as any).uid
  );

  fileList.value.splice(fileIndex, 1, {
    name: name,
    url: import.meta.env.VITE_APP_BASE_API + path,
  } as UploadUserFile);

  const fileListCom = computed(() => {
    return fileList.value.map(item => {
      return {
        ...item,
        url: import.meta.env.VITE_APP_BASE_API + item.url,
      }
    })
  })

  let result = null;
  const imgArr = fileList.value.map((file) => file.url);

  // if (imgArr.length > 0) {
  //   result = imgArr[0];
  // }

  result = imgArr;

  emit(
    "update:modelValue",
    result
  );
}

/**
 * 限制用户上传文件的格式和大小
 */
function handleBeforeUpload(file: UploadRawFile) {
  if (
    !["image/jpeg", "image/png", "image/gif", "image/bmp"].includes(file.type)
  ) {
    ElMessage.warning("上传图片只能是 JPG、PNG、GIF、BMP 格式!");
    return false;
  }
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于2M");
    return false;
  }
  return true;
}

/**
 * 预览图片
 */
const previewImg: UploadProps["onPreview"] = (uploadFile) => {
  previewImgUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.upload {
  :deep(.el-upload-list) {
    margin: 0;

    .el-upload-list__item {
      margin: 0;
    }

    .el-icon--close-tip {
      display: none!important;
    }
  }
}
</style>
